package com.ruoyi.controller.middlesign;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rfp.ws.utils.ECCFileUtils;
import com.rfp.ws.utils.ECCUtils;
import org.apache.commons.io.FileUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.dom4j.Attribute;
import org.dom4j.Element;

import java.io.*;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author zeo
 * @explain 中征平台工具类
 * @date 2021/3/15 16:29
 */
public class MiddlesUtils {

    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-hhmmss");

    /**
     * 获取UUID
     *
     * @return
     */
    public static String getUUid() {
        return UUID.randomUUID().toString().replace("-", "").toLowerCase();
    }

    /**
     * 获取年月日 YYYYMMDD
     */
    public static String getYearMonthDay() {
        Date date = new Date();
        String[] array = simpleDateFormat.format(date).split("-");
        return array[0];
    }

    /**
     * 获取时分秒 HHMMSS
     */
    public static String getTime() {
        Date date = new Date();
        String[] array = simpleDateFormat.format(date).split("-");
        return array[1];
    }


    public static void dom4j2Json(Element element, JSONObject json) {
        //如果是属性
        for (Object o : element.attributes()) {
            Attribute attr = (Attribute) o;
            if (!isEmpty(attr.getValue())) {
                json.put("@" + attr.getName(), attr.getValue());
            }
        }
        List<Element> chdEl = element.elements();
        //如果没有子元素,只有一个值
        if (chdEl.isEmpty() && !isEmpty(element.getText())) {
            json.put(element.getName(), element.getText());
        }
        //有子元素
        for (Element e : chdEl) {
            //子元素也有子元素
            if (!e.elements().isEmpty()) {
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    //如果此元素已存在,则转为jsonArray
                    if (o instanceof JSONObject) {
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
            } else {//子元素没有子元素
                for (Object o : element.attributes()) {
                    Attribute attr = (Attribute) o;
                    if (!isEmpty(attr.getValue())) {
                        json.put("@" + attr.getName(), attr.getValue());
                    }
                }
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }

    public static void emptyFileTxt(String path) {
        File file = new File(path);
        try {
            FileUtils.writeStringToFile(file, "", false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Additional(String text, String filePath) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(filePath), true), "utf-8"));
            out.write(text);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean isEmpty(String str) {

        if (str == null || str.trim().isEmpty() || "null".equals(str)) {
            return true;
        }
        return false;
    }

    public static int getRandomNumber() {
        return (int) (1 + Math.random() * (100 - 1 + 1));
    }


    public static String getFileText(String path) {
        try {
            File file = new File(path);
            String text = "";
            if (file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String s = null;
                while ((s = br.readLine()) != null) {
                    text += s + "-----";
                }
                br.close();
            }
            return text;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 中征平台https请求提交
     *
     * @param wsdl
     * @param methodName
     * @param data
     * @return
     * @throws Exception
     */
    public static String callHttpService(String wsdl, String methodName, Object... data) throws Exception {
        String returnStr = null;
        try {
            JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
            Client client = clientFactory.createClient(wsdl);

            //需要添加超时参数等,添加如下代码
            // 获取静态映射
            HTTPConduit conduit = (HTTPConduit) client.getConduit();
            // 创建策略
            HTTPClientPolicy policy = new HTTPClientPolicy();
            //设置允许分块传输
            policy.setAllowChunking(false);
            // 连接服务器超时时间3分钟
            policy.setConnectionTimeout(180000);
            //等待服务器响应超时时间3分钟
            policy.setReceiveTimeout(180000);
            //将策略设置进端点
            conduit.setClient(policy);

            Object[] result = client.invoke(methodName, data);
            returnStr = result[0].toString();

        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnStr;
    }

    /**
     * 凭证号处理
     *
     * @param map
     * @return
     */
    public static String VoucherNumberProcessing(Map map) {
        String ORDER_AMT;
        if (map.get("EXPLANATION").toString().indexOf("调整凭证") == -1) {
            //不是调整凭证 还是等于原值
            ORDER_AMT = map.get("ORDER_AMT").toString();
        } else {
            //是调整凭证
            if (map.get("LOCALDEBITAMOUNT").toString().equals("0") || map.get("LOCALDEBITAMOUNT").toString().equals("0.00")) {
                //调整凭证是不是0,是0等于原值
                ORDER_AMT = map.get("ORDER_AMT").toString();
            } else {
                //不是0，先判断是不是负数
                if (map.get("LOCALDEBITAMOUNT").toString().indexOf("-") == -1) {
                    //要是正数，改成负数
                    ORDER_AMT = "-" + map.get("LOCALDEBITAMOUNT").toString();
                } else {
                    //要是负数，改成正数
                    ORDER_AMT = map.get("LOCALDEBITAMOUNT").toString().substring(1, map.get("LOCALDEBITAMOUNT").toString().length());
                }
            }
        }
        return ORDER_AMT;
    }




}
